#include "pagecontroller.h"
#include <QDebug>
PageController::PageController(QStackedWidget *stackedWidget, QObject *parent)
    : QObject(parent), _stackedWidget(stackedWidget){
    if(!_stackedWidget) qDebug() << "初始化PageController时未添加QStackedWidget " << (parent ? parent->objectName() : "");
}

QString PageController::addPage(MyPushButton *btn, QWidget *page) {
    if(btn == nullptr) {
        qDebug() << "添加了一个空按钮至界面管理器";
        return "";
    }
    QString id = createId();
    _pageId[id] = {btn, page};
    connect(btn, &QPushButton::clicked, this, [this, id]{
        if (currentPageId() != id)
            switchToPage(id);
    });
    if (_stackedWidget && page)
        _stackedWidget->addWidget(page);
    return id;
}

void PageController::removePage(const QString &pageId)
{
    auto it = _pageId.find(pageId);
    if (it == _pageId.end())
        return;
    if (_stackedWidget && it->second)
        _stackedWidget->removeWidget(it->second);
    if (_stackedWidget && currentPageId() == pageId)
        _currentPageId = "";
    _pageId.erase(it);
}

void PageController::switchToPage(const QString &pageId)
{
    auto it = _pageId.find(pageId);
    if (it == _pageId.end()) return;
    if (currentPageId() != "" && _pageId[currentPageId()].first)
        _pageId[currentPageId()].first->check(false);
    it->first->check(true);
    if (_stackedWidget && it->second)
        _stackedWidget->setCurrentWidget(it->second);
    _currentPageId = pageId;
}

QString PageController::currentPageId() const {
    return _currentPageId;
}

QString PageController::createId() const {
    return "page-" + QUuid::createUuid().toString().slice(1, 36);
}
